//
//  HMElem.swift
//  HealthMonitoring
//
//  Created by YTYanK on 2018/10/26.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import SwiftyJSON

class HMElem: NSObject {
    
    /**
     HMElem实例
     */
    static let share: HMElem = {
        return HMElem()
    }()
    
     /**
       发一条固定信息，用于建立会话
        TIMConversation 对象
      */
    class func foundConversation(_ conversation: TIMConversation) {
        HMElem.structureMessage(conversation, elemType: TIMTextElem.classForCoder(), value: "医生您好，我有问题需要咨询。")
        
    }
    // sendTextMessage
    class func textMessage(_ conversation: TIMConversation, text: String) {
//        HMElem.structureMessage(conversation, elemType: TIMTextElem.classForCoder(), value: text)
       
    }
    
    /**
     构建信息
     */
    class func structureMessage(_ conversation: TIMConversation, elemType: AnyClass, value: Any) {
        //构建消息
        let text_elem = TIMTextElem()
        text_elem.text = (value as! String)
        //创建一条消息
        let mge = TIMMessage()
        mge.add(text_elem)
        conversation.send(mge, succ: {
            print("发送成功")
        }) { (code, err) in
            print("失败")
        }
    }
    
    class func structureMessage(_ conversation: TIMConversation, elemType: AnyClass, value: Any, succ: @escaping TIMSucc, fail: @escaping TIMFail) {
        //构建消息
         let mge = TIMMessage()
        if elemType == TIMTextElem.self {  // 文本
            let text_elem = TIMTextElem()
            text_elem.text = (value as! String)
            //创建一条消息
            mge.add(text_elem)
         
        }else if elemType == TIMImageElem.self { //图片
            let img_elem = TIMImageElem()
            img_elem.path = (value as! String)
            mge.add(img_elem)
        }else if elemType == TIMSoundElem.self { //语音
            let sound_elem = TIMSoundElem()
            let t =  value as! (String, Double)
            sound_elem.path = t.0
            sound_elem.second = Int32(t.1)
            mge.add(sound_elem)
            
        }else if elemType == TIMCustomElem.self {
            let custom_elem = TIMCustomElem()
            custom_elem.data = value as! Data
            custom_elem.desc = "药物建议"
//            let pushInfo = TIMOfflinePushInfo()
//            pushInfo.desc = "药物建议"
//            pushInfo.ext = "嘻嘻嘻嘻嘻"
//            mge.set   //setOfflinePushInfo(pushInfo)
            mge.add(custom_elem)
        }else {
            
        }
        
        
        conversation.send(mge, succ: {
            print("发送成功")
            succ()
        }) { (code, err) in
            print("失败")
            fail(code, err)
        }
    }
    
    
    /**
     消息解析
     isOutGoing = 消息归属
     契合IM API 获取数据
     */
    
    @available(iOS, introduced: 7.0, deprecated: 9.0, message: "Use -throughServiceAnalysimMessage(list:, sort:, profile:, elemBlock:)")
    class func analysisMessage(list: [Any], sort: Bool = true, doctorProfile:TIMUserProfile?, elemBlock:(TIMElem, HMImUserInfo, Bool, AnyClass)->()) {
        
        for index in 0..<list.count {
            
            let newIndex = (list.count - 1) - index
            // 消息排序， 获取方式
            let sortNum =  sort ? newIndex : index
            let message = list[sortNum] as! TIMMessage
            // 消息条数
            let cnt = message.elemCount()
            // 用户信息
            let info = HMImUserInfo()
            // 判断消息归属，默认自己发出
            var going: Bool = true
            if message.sender() == HMLoginParam.share.getCurrentId {
                going = true //我发过去的消息
                info.im_userId = HMLoginParam.share.getCurrentId
            }else {
                going = false //对方发来的消息
                 // 直接传
                if doctorProfile != nil {
                    info.im_displayName = doctorProfile!.nickname
                    info.urlImg = configure.shareConfigure.IP_diagonal + doctorProfile!.faceURL
                    info.im_userId = doctorProfile!.identifier
                }
            }
            
            for i in 0..<cnt {
                let elem = message.getElem(i)
               
                var _elemType :AnyClass
                if (elem?.isKind(of: TIMTextElem.classForCoder()))! {
                     _elemType = TIMTextElem.classForCoder()
                }else if (elem?.isKind(of: TIMImageElem.classForCoder()))! {
                      _elemType = TIMImageElem.classForCoder()
                }else if (elem?.isKind(of: TIMSoundElem.classForCoder()))! {
                     _elemType = TIMSoundElem.classForCoder()
                }else {
                     _elemType = TIMElem.classForCoder()
                }
                
                   elemBlock(elem!, info, going, _elemType)
            }
            
            
        }
    }
    

    
    
    /// 通过服务器来填充解析数据
    ///  消息解析
    /// isOutGoing = 消息归属
    /// profile = 用户信息
    /// elemBlock (序号,发送内容，发送人信息，是谁发送，信息条数)
    class func serviceAnalysimMessage(list:[Any], sort: Bool = true, profile: JSON, elemBlock:(Int, TIMMessage, HMImUserInfo, Bool)->()) {
        
        for index in 0..<list.count {
            
            let newIndex = (list.count - 1) - index
            // 消息排序， 获取方式
            let sortNum =  sort ? newIndex : index
            let message = list[sortNum] as! TIMMessage
            // 消息条数
            let cnt = message.elemCount()
            // 用户信息
            let info = HMImUserInfo()
            // 判断消息归属，默认自己发出
            var going: Bool = true
            if message.sender() == HMLoginParam.share.getCurrentId {
                going = true //我发过去的消息
                info.im_userId = HMLoginParam.share.getCurrentId
               
//                info.im_displayName =
//                info.urlImg =  configure.shareConfigure.IP_diagonal +  "\(HMLoginParam.share.getCurrentImage)"
            }else {
                going = false //对方发来的消息
                // 直接传
                //                if doctorProfile != nil {
                //                    info.im_displayName = doctorProfile!.nickname
                //                    info.urlImg = configure.shareConfigure.IP_diagonal + doctorProfile!.faceURL
                //                    info.im_userId = doctorProfile!.identifier
                //                }
                if profile != nil {
                    
                    if profile["illness"] != nil { //通过是否有病例来判断是否用户，而不是医生
                        info.im_displayName = profile["nickname"].stringValue
                        info.im_userId = profile["userId"].stringValue
                        info.urlImg =  configure.shareConfigure.IP_diagonal +  profile["iconUrl"].stringValue
                    }else {
                        info.im_displayName = profile["doctorName"].stringValue
                        info.im_userId = profile["doctorId"].stringValue
                        info.urlImg =  configure.shareConfigure.IP_diagonal +  profile["doctorIcon"].stringValue
                    }
                }
                
                
                
               
                
            }
            

            
            elemBlock(index,message,info,going)
            
            //(序号,发送内容，发送人信息，是谁发送，类型)
//            elemBlock(index,elem,info,going,_elemType)
//             elemBlock(index, info, going, _elemType)
        }
    }
    
    // 自动判断
   /* func automaticallyJudge(_ classType: AnyClass, _ elem:TIMElem, _ userInfo:HMImUserInfo, _ isOutGoing:Bool) {
        if classType == TIMTextElem.self {
            let text_elem = elem as! TIMTextElem
            let mesg = MessageModel(text: text_elem.text, isOutGoing: isOutGoing)
            
            mesg.messageStatus = .success
            mesg.fromUser = userInfo
            self.messageCollectionView.appendMessage(with: mesg)
            
        }else if classType == TIMImageElem.self {
            let img_elem = elem as! TIMImageElem
            
            //                print("=====>>", img_elem.imageList)
            
            if !(img_elem.path.contains("http://")) {
                // 图片保存路径
                let docPath: String = "\(NSHomeDirectory())/Documents/"
                
                /* 保存本图片的所有规格，目前最多包含三种规格: 缩略图、大图、原图，
                 每种规格保存在一个TIMImage对象中 */
                let imgList = img_elem.imageList
                // 不循环
                //  var i = 0
                
                if imgList?.count != 0 {
                    //                        let url =  URL.init(string:  img_elem.path)  //获取原图路径
                    let  filePath =  InstantMessaging.getUserFilePath()
                    
                    let url = String.interceptString(value: img_elem.path, character: "/", isPrefix: false, isFirst: false)
                    let newUrl = url.suffix(url.count - 1)
                    
                    // 设置保存的文件名称  原图名称  + _1x （缩略图） ， _2x (大图)
                    var pic_path = docPath  + "\(newUrl)_1x.jpg"   // 不带
                    let file = filePath.appendingPathComponent("\(newUrl)_1x.jpg")  //带  fill://
                    
                    print("======>", pic_path , "\n ====>", file)
                    
                    do { // 判断路径上d是否有原文件
                        try Data.init(contentsOf: file)
                        
                        print("存在")
                        let mesg = MessageModel.init(imagePath: pic_path, isOutGoing: isOutGoing)
                        mesg.messageStatus = .success
                        mesg.fromUser = userInfo
                        self.messageCollectionView.appendMessage(with: mesg)
                        
                    }catch {
                        print("path is not exist")
                        
                        // 拿缩略图
                        let image = imgList![0] as! TIMImage
                        // 下载
                        image.getImage(pic_path, succ: {
                            print("成功====>>", image, pic_path)
                            let mesg = MessageModel.init(imagePath: pic_path, isOutGoing: isOutGoing)
                            mesg.messageStatus = .success
                            mesg.fromUser = userInfo
                            self.messageCollectionView.appendMessage(with: mesg)
                        }, fail: { (code, err) in
                            print("失败===>>", image)
                        })
                        
                        
                    }
                    
                }else {
                    print("img list count is zero  (没有图组)")
                }
            }else {
                print(" is img path Illegal format (格式不对)")
            }
            
        }
        else if classType == TIMSoundElem.self {
            let sound_elem = elem as! TIMSoundElem
            
            // 保存语音的路径
            var docPath: String = "\(NSHomeDirectory())/Documents/"
            
            //                var pic_path = docPath    //+ "\(newUrl)_1x.jpg"   // 不带
            print("=======>>>>", sound_elem.path)
            
            
            
            if sound_elem.path != "" && sound_elem.path != nil {
                
                //截取路径中的文件名称
                let url = String.interceptString(value: sound_elem.path, character: "/", isPrefix: false, isFirst: false)
                let fillName = url.suffix(url.count - 1)
                print("------>文件名称", fillName)
                let  filePath =  InstantMessaging.getUserFilePath()
                let file = filePath.appendingPathComponent(String(fillName))
                
                if InstantMessaging.isFileExist(fileName: String(fillName)) {
                    print("存在路径")
                    //                        let path =  pic_path + fillName
                    let mesg = MessageModel.init(voicePath: "\(file)", duration: CGFloat(sound_elem.second), isOutGoing: isOutGoing)    // init(imagePath: path, isOutGoing: isOutGoing)
                    mesg.messageStatus = .success
                    mesg.fromUser = userInfo
                    self.messageCollectionView.appendMessage(with: mesg)
                }else {
                    //                        print("1111")
                    
                    let now:Date = Date()
                    let dateFormatter = DateFormatter()
                    dateFormatter.dateFormat = "yyyy-MM-dd-hh-mm-ss"
                    // 设置保存的文件名称
                    let path = docPath + "\(dateFormatter.string(from: now))-OtherSound.wav"
                    sound_elem.getSoundToFile(path, succ: {
                        
                        let mesg = MessageModel.init(voicePath: "\(file)", duration: CGFloat(sound_elem.second), isOutGoing: isOutGoing)    // init(imagePath: path, isOutGoing: isOutGoing)
                        mesg.messageStatus = .success
                        mesg.fromUser = userInfo
                        self.messageCollectionView.appendMessage(with: mesg)
                        
                    }, fail: { (code, err) in
                        print("获取失败")
                    })
                    NSAttributedString.init(fileURL: <#T##URL#>, options: <#T##[AnyHashable : Any]#>, documentAttributes: <#T##AutoreleasingUnsafeMutablePointer<NSDictionary?>?#>)
                   // @available(*, deprecated, renamed: "ExpressibleByStringLiteral")
                }
                
                
                
            }else {
                print("sound path is not (没有文件路径)")
            }
        }
        else if classType == TIMFaceElem.self {
            
            
            let face_elem = elem as! TIMFaceElem
            let num = face_elem.index
            let path = Bundle.main.path(forResource: "emoticon/\(num)", ofType: "gif")
            let data =  NSData.init(contentsOfFile: path!)
            let newdata = data! as Data
            
            
            //            print("elem===", NSString.init(data: newdata, encoding: String.Encoding.utf8.rawValue))
            //            let ui =   UIImageView.init(image: UIImage.init(data: newdata))
            //            print("elem===",ui)
            //
            //
            //            ui.frame = CGRect.init(x: 0, y: 0, width: 20, height: 20)
            //           self.view.addSubview(ui)
            
            let textAttachment = NSTextAttachment.init(data: newdata, ofType: "gif")
            let str = NSAttributedString.init(attachment: textAttachment)
            //            textAttachment.image = UIImage.init(data: newdata)
            let textView = UITextView.init()
            textView.attributedText = str
            
            let mesg = MessageModel(text: textView.text, isOutGoing: isOutGoing)
            mesg.messageStatus = .success
            mesg.fromUser = userInfo
            self.messageCollectionView.appendMessage(with: mesg)
            
            
            
        }
        else {
            print("(其他格式文件)")
        }
        
    } */
}
